package com.itjcloud.iot.gateway.config;

import com.itjcloud.iot.gateway.client.IotClient;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.event.EnableBodyCachingEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

@Configuration
public class WebClientConfig {


    @Resource
    private ApplicationEventPublisher publisher;
    @Resource
    private GatewayProperties gatewayProperties;


    @LoadBalanced
    @Bean
    public WebClient.Builder loadBalancedWebClientBuilder() {
        return WebClient.builder();
    }
    /**
     * 配置iot的客户端
     *
     * @return iot客户端
     */
    @Bean
    public IotClient iotClient(WebClient.Builder webClientBuilder) {
        WebClient webClient = webClientBuilder.baseUrl("http://saas-iot").build();
        WebClientAdapter adapter = WebClientAdapter.create(webClient);
        HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
        return factory.createClient(IotClient.class);
    }

    @PostConstruct
    public void init() {
        gatewayProperties.getRoutes().forEach(routeDefinition -> {
            // 对 spring cloud gateway 路由配置中的每个路由都启用 AdaptCachedBodyGlobalFilter
            EnableBodyCachingEvent enableBodyCachingEvent = new EnableBodyCachingEvent(new Object(),
                    routeDefinition.getId());
            publisher.publishEvent(enableBodyCachingEvent);
        });
    }


}
